#!/bin/sh

# Run this script from the top or tools directory to update the MPFR version.

set -e

LC_ALL=C
export LC_ALL

if [ $# -lt 3 ] || [ $# -gt 5 ]; then
  echo >&2 "Usage: $0 <major> <minor> <patchlevel> [ <suffix> [ - ] ]"
  echo >&2 "(use 5 arguments to produce patches for releases)"
  exit 1
fi

# Examples:
#   ./update-version 2 3 0 dev
#   ./update-version 2 3 0 rc1
#   ./update-version 2 3 0
#   ./update-version 2 3 0 p1 -

dir=`pwd`
[ -d src ] || [ "`basename \"$dir\"`" != tools ] || cd ..

replace()
{
  if [ ! -h "$2" ] && [ -r "$2" ] && [ -w "$2" ]; then
    err=`perl -pi -e "$1" "$2" 2>&1 >/dev/null`
    if [ -n "$err" ]; then
      printf >&2 "Error from perl:\n%s\n" "$err"
      exit 2
    fi
  else
    printf >&2 "Error: %s is not a readable/writable file\n" "$2"
    exit 2
  fi
}

vers="$1.$2.$3"
full="$vers${4:+-$4}"
replace "s/(?<=#define MPFR_VERSION_MAJOR ).*/$1/; \
         s/(?<=#define MPFR_VERSION_MINOR ).*/$2/; \
         s/(?<=#define MPFR_VERSION_PATCHLEVEL ).*/$3/; \
         s/(?<=#define MPFR_VERSION_STRING ).*/\"$full\"/" src/mpfr.h
replace "s/(?<=return \").*\"/$full\"/" src/version.c
echo $full > VERSION

if [ $# -lt 5 ]; then
  # Up to 4 arguments...
  u="https://www.mpfr.org/mpfr-"
  replace "s/(?<=\@set VERSION ).*/$full/" doc/mpfr.texi
  replace "s,MPFR [\d.]+( web page \@url\{$u)[\d.]+/,MPFR $vers\${1}$vers/," \
    doc/mpfr.texi
  replace "s/(?<=AC_INIT).*/([MPFR],[$full])/" configure.ac
  replace "s,(?<=$u).*?/,$vers/," INSTALL
fi

echo "MPFR version successfully updated."
echo "Don't forget to update MPFR libtool version in 'src/Makefile.am'."
